export default{
  namespaced:true,
  
  state:()=>({
    cart:JSON.parse(uni.getStorageSync('cart')||'[]')
  }),
  
  mutations:{
    updateSelectState(state,status){
      state.cart.forEach(x=>x.goods_state=status)
      this.commit('m_cart/saveToStorage')
    },
    deleteGoods(state,goods){
      state.cart = state.cart.filter(x=>x.goods_id!==goods.goods_id)
      this.commit('m_cart/saveToStorage')
    },
    updateGoodsState(state,goods){
      const findResult = state.cart.find(x=>x.goods_id===goods.goods_id)
      if(findResult){
        findResult.goods_state = goods.goods_state
      }
      this.commit('m_cart/saveToStorage')
    },
    updateGoodsCount(state,goods){
      const findResult = state.cart.find(x=>x.goods_id===goods.goods_id)
      if(findResult){
        findResult.goods_count=goods.goods_count
      }
      this.commit('m_cart/saveToStorage')
    },
    //添加购物车
    addToCart(state,goods){
      //现在cart数组中查找
      const findResult = state.cart.find(x=>x.goods_id==goods.goods_id)
      if(!findResult){
        //找不到undefind 第一次添加
        state.cart.push(goods)
      }else{
        //否则数量+1
        findResult.goods_count++
      }
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    }
  },
  
  getters:{
    total(state){
      // let count=0
      // state.cart.forEach(x=>count+=x.goods_count)
      // return count
      return state.cart.reduce((total,item)=>total+=item.goods_count,0)
    },
    totalMoney(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
    },
    selectTotal(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
    }
  }
}